package hos.kotlin

import java.text.DecimalFormat

/**
 * <p>Title: IntExt </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2022/6/26 14:52
 * @version : 1.0
 */


fun Double?.format(format: String = "#.##"): String {
    return try {
        val orEmpty: Double = this.asDouble()
        val numberFormat = DecimalFormat(format)
        val result = numberFormat.format(orEmpty)
        if (result == null || result.isEmpty()) {
            return "0"
        }
        if (result == ".00") {
            return "0"
        }
        if (result.contains(".") && "." == result.substring(0, 1)) {
            "0$result"
        } else result
    } catch (e: Exception) {
        e.printStackTrace()
        "0"
    }
}

fun Float?.format(format: String = "#.##"): String {
    return try {
        val orEmpty: Float = this.asFloat()
        val numberFormat = DecimalFormat(format)
        val result = numberFormat.format(orEmpty)
        if (result == null || result.isEmpty()) {
            return "0"
        }
        if (result == ".00") {
            return "0"
        }
        if (result.contains(".") && "." == result.substring(0, 1)) {
            "0$result"
        } else result
    } catch (e: Exception) {
        e.printStackTrace()
        "0"
    }
}


